package com.sekill.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seckill.common.core.utils.bean.BeanUtils;
import com.seckill.common.redis.service.RedisService;
import com.sekill.goods.entity.Seckill;
import com.sekill.goods.entity.Stock;
import com.sekill.goods.entity.TbSku;
import com.sekill.goods.mapper.SeckillMapper;
import com.sekill.goods.service.ISeckillService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sekill.goods.service.IStockService;
import com.sekill.goods.service.ITbSkuService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huhu
 * @since 2021-06-21
 */
@Service
public class SeckillServiceImpl extends ServiceImpl<SeckillMapper, Seckill> implements ISeckillService {
    @Autowired
    private ISeckillService iSeckillService;

    @Autowired
    private ITbSkuService iTbSkuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IStockService iStockService;

    private static final Logger LOGGER = LoggerFactory.getLogger(SeckillServiceImpl.class) ;
    private static final String PATH = "/templates/" ;
    @Override
    public void ftlToHtml() throws Exception {
        // 创建配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 设置模板路径
        String classpath = this.getClass().getResource("/").getPath();
        configuration.setDirectoryForTemplateLoading(new File(classpath + PATH));
        // 加载模板
        Template template = configuration.getTemplate("my-page.ftl");
        // 数据模型
        Map<String, Object> map = new HashMap<>();
        map.put("myTitle", "页面静态化(PageStatic)");
        map.put("goodsList",getlist());
        // 静态化页面内容
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        LOGGER.info("content:{}",content);
        InputStream inputStream = IOUtils.toInputStream(content,"UTF-8");
        // 输出文件
        File file = new File("");
        String canonicalPath = file.getCanonicalPath();
        FileOutputStream fileOutputStream = new FileOutputStream(new File(canonicalPath+"/seckill-modules/seckill-goods/src/main/resources/templates/goods.html"));
        IOUtils.copy(inputStream, fileOutputStream);
        // 关闭流
        inputStream.close();
        fileOutputStream.close();
    }

    @Override
    public Seckill getbyids(Integer skuId) throws IOException, TemplateException {

            //根据skuId获取秒杀商品详情
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("sku_id",skuId);
            Seckill goods  = iSeckillService.getOne(queryWrapper);
            Long skuId1 = goods.getSkuId();
            TbSku sku = iTbSkuService.getById(skuId1);
            if (sku.getId().equals(goods.getSkuId())){
                goods.setTitle(sku.getTitle());
                goods.setImages(sku.getImages());
            }
        //开始时间
        long start = goods.getSeckillCreatedate().getTime();
        //结束时间
        long end = goods.getSeckillEnddate().getTime();
        //时间戳 （毫秒值）
        long now = System.currentTimeMillis();
        int shangjiastatus=0;
        int times=0;
        if(now < start){//秒杀没开始 倒计时时间
            shangjiastatus=0;
            times= (int) ((start-now)/1000);
        }else if(now > end){//秒杀已经结束
            shangjiastatus=2;
            times=-1;
        }else{//秒杀进行中
            shangjiastatus=1;
            times=0;
        }
        goods.setStatus(shangjiastatus);
        goods.setTimes(times);

        return goods;
    }

    @Override
    public List<Seckill> getlist() {
        QueryWrapper queryWrapper = new QueryWrapper();
        //根据上架的商品查询
        queryWrapper.eq("status",1);
        List<Seckill> list = iSeckillService.list(queryWrapper);
        for (Seckill seckill :list){
            TbSku goods = iTbSkuService.getById(seckill.getSkuId());
            //判断商品和秒杀商品id是否一致
            if (goods.getId().equals(seckill.getSkuId())){
                //获取商品的标题 存入秒杀商品对象
                seckill.setTitle(goods.getTitle());
                seckill.setImages(goods.getImages());
            }
            /*//获取库存表
            List<Stock> stocks = iStockService.list();
            for (Stock stock: stocks){
                //判断商品和库存id是否一致
                if (stock.getSkuId().equals(seckill.getSkuId())){
                    //将库存id和需要秒杀库存的数量存入redis
                    ValueOperations opsForValue = redisTemplate.opsForValue();
                    opsForValue.set(stock.getSkuId()+"",stock.getSeckillStock());
                }

            }*/
        }
        return list;
    }

    @Override
    public void ftlToHtml(Integer skuId) throws Exception {



        // 创建配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 设置模板路径
        String classpath = this.getClass().getResource("/").getPath();
        configuration.setDirectoryForTemplateLoading(new File(classpath + PATH));
        // 加载模板
        Template template = configuration.getTemplate("order.ftl");
        // 数据模型
        Map<String, Object> map = new HashMap<>();
        map.put("myTitle", "页面静态化(PageStatic)");
        map.put("goods",getbyids(skuId));
        // 静态化页面内容
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        LOGGER.info("content:{}",content);
        InputStream inputStream = IOUtils.toInputStream(content,"UTF-8");
        // 输出文件
        File file = new File("");
        String canonicalPath = file.getCanonicalPath();
        FileOutputStream fileOutputStream = new FileOutputStream(new File(canonicalPath+"/seckill-modules/seckill-goods/src/main/resources/templates/search"+skuId+".html"));
        IOUtils.copy(inputStream, fileOutputStream);
        // 关闭流
        inputStream.close();
        fileOutputStream.close();


    }
    //修改秒杀商品状态
    @Override
    public boolean updateSeckillStatus(Integer status,Long skuId) {
        int num = getBaseMapper().updateSeckillStatus(status,skuId);
        return num>0;
    }
}
